package com.ruoyi.project.util;

import com.alibaba.fastjson.JSON;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.project.interface_log.domain.InterfaceLog;
import com.ruoyi.project.interface_log.service.IInterfaceLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ScheduledApiLoggingAspect {

    @Autowired
    private IInterfaceLogService interfaceLogService;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(logScheduledApiRequest)")
    public Object logScheduledApiRequest(ProceedingJoinPoint joinPoint, LogScheduledApiRequest logScheduledApiRequest) throws Throwable {
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        // 获取请求 URL
        String name = null;
        String ip = null;
        String json = null;
        // 调用目标方法并获取返回结果
        Object responseBody = null;
        if (args.length > 0 && args[0] instanceof String) {
            ip = (String) args[0];
            name = (String) args[1];
            json = (String) args[2];
        }
        InterfaceLog interfaceLog = new InterfaceLog();
        try {
            joinPoint.proceed();
            String jsons = JsonUtils.isJson(responseBody.toString()) ? JsonUtils.toJson(responseBody) : responseBody.toString();
            interfaceLog.setId(UUID.randomUUID().toString());
            interfaceLog.setSend(json);
            interfaceLog.setResult(jsons);
            interfaceLog.setIp(ip);
            interfaceLog.setSystem(name);
            String s = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            interfaceLog.setTime(s);
            interfaceLogService.insertInterfaceLog(interfaceLog);
        } catch (Exception e) {
            interfaceLog.setId(UUID.randomUUID().toString());
            interfaceLog.setSend(json);
            interfaceLog.setResult(e.getMessage().toString());
            interfaceLog.setIp(ip);
            interfaceLog.setSystem(name);
            String s = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            interfaceLog.setTime(s);
            interfaceLogService.insertInterfaceLog(interfaceLog);
        }
        // 返回目标方法的结果
        return responseBody;
    }


}
